package icedot.library.common.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

import java.util.ArrayList;

/**
 * Created by IceDot on 2018-02-05.
 */

public class DrawView extends SurfaceView implements SurfaceHolder.Callback, Runnable
{
    private Bitmap cacheBitmap = null;
    private int _width;
    private int _height;
    private int _record = 0;
    private ArrayList<PointF> points;
    private boolean _isRecord = false;
    private ArrayList<ArrayList<PointF>> _allList = new ArrayList<>();
    /**
     * 是否处于绘制状态
     */
    private boolean mIsDrawing;
    /**
     * 帮助类
     */
    private SurfaceHolder mHolder;
    /**
     * 画布
     */
    private Canvas mCanvas;
    /**
     * 路径
     */
    private Path mPath;
    /**
     * 画笔
     */
    private Paint mPaint;

    public DrawView(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        initView();
    }

    public DrawView(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        initView();
    }

    public DrawView(Context context)
    {
        super(context);
        initView();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        /**
         * getMode获取测量模式(下面3种) 和 getSize获取测量值
         *
         * EXACTLY：当宽高值设置为具体值时使用，如100dp、match_parent等，此时取出的size是精确的尺寸；
         * AT_MOST：当宽高值设置为wrap_content时使用，此时取出的size是控件最大可获得的空间；
         * UNSPECIFIED：当没有指定宽高值时使用（很少见）。
         *
         * */
        //测量模式_宽
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        //测量模式_高
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        //宽度
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        //高度
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);

        //设置view宽度
        //如果布局中给出了准确的宽度，直接使用宽度，否则设置图片宽度为view宽度
        if (widthMode == MeasureSpec.EXACTLY)
        {
            _width = widthSize;
        }
        else
        {
            _width = 500;
        }
        //设置view高度同上
        if (heightMode == MeasureSpec.EXACTLY)
        {
            _height = heightSize;
        }
        else
        {
            _height = 500;
        }
        //重新设置view的宽高
        setMeasuredDimension(_width, _height);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {

        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction())
        {
            case MotionEvent.ACTION_DOWN:
            {
//                _isRecord = true;
//                points = new ArrayList<>();
//                PointF pt = new PointF(event.getX(), event.getY());
//                points.add(pt);
                _record++;
                mPath.moveTo(x, y);
            }
                break;
            case MotionEvent.ACTION_MOVE:
            {
//                if (_isRecord)
//                {
//                    PointF pt = new PointF(event.getX(), event.getY());
//                    points.add(pt);
//                }
                _record++;
                mPath.lineTo(x, y);
            }
                break;
            case MotionEvent.ACTION_UP:
            {
                _record++;
//                _isRecord = false;
//                PointF pt = new PointF(event.getX(), event.getY());
//                points.add(pt);
//                _allList.add(points);
            }
                break;
            default:
                break;
        }

        return true;
    }

    private void initView()
    {
        mHolder = getHolder();
        mHolder.addCallback(this);
        setFocusable(true);
        setFocusableInTouchMode(true);
        this.setKeepScreenOn(true);

        mPath = new Path();

        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mPaint.setColor(Color.BLACK);
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setStrokeWidth(5);
        _record = 0;
    }

    @Override
    public void run()
    {
        long start = System.currentTimeMillis();
        while (mIsDrawing)
        {
            draw();
        }
        long end = System.currentTimeMillis();
        if (end - start < 100)
        {
            try
            {
                Thread.sleep(100 - (end - start));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void surfaceCreated(SurfaceHolder arg0)
    {
        mIsDrawing = true;
        new Thread(this).start();
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
    {
        _width = width;
        _height = height;
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder arg0)
    {
        mIsDrawing = false;

    }

    private void draw()
    {
        try
        {
            mCanvas = mHolder.lockCanvas();
            if(mCanvas != null)
            {
                mCanvas.drawColor(Color.WHITE);
                mCanvas.drawPath(mPath, mPaint);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (mCanvas != null)
            {
                mHolder.unlockCanvasAndPost(mCanvas);
            }
        }
    }

    /**
     * 清除内容
     */
    public void clean()
    {
        initView();
    }

    public Bitmap saveToBitmap()
    {
        if(_record < 4)
        {
            return null;
        }
        Canvas canvas = new Canvas();
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.BLACK);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(5);
        cacheBitmap = Bitmap.createBitmap(_width,_height, Bitmap.Config.ARGB_8888);
        canvas.setBitmap(cacheBitmap);
        canvas.drawColor(Color.WHITE);
        canvas.drawPath(mPath, paint);
        return cacheBitmap;
    }
}